package tmproject.hlhj.fhp.cartrans.customVIews

import android.Manifest
import android.app.Dialog
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.dialog_imgcheck.*
import tmproject.hlhj.fhp.cartrans.R
import tmproject.hlhj.fhp.cartrans.http.Urls
import tmproject.hlhj.fhp.cartrans.utils.FileUtils
import tmproject.hlhj.fhp.cartrans.utils.TimeUtils

class ImgCheckDialog(private val c:Context,private val img:String?,private val tittle:String?,
                     private val time:String?) :Dialog(c, R.style.MyDialog) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_imgcheck)
        Glide.with(c)
                .load(Urls.ImgBase+img)
                .into(imgCheck)

        tvTittle.text=tittle
        if (TextUtils.isEmpty(time)){
            isOk.visibility=View.GONE
        }else{
            tvTime.text="到期日期：${time}"
            if (TimeUtils.timeLeft(TimeUtils.getTime(time))){
                isOk.visibility=View.VISIBLE
            }else{
                isOk.visibility=View.GONE
            }
        }



        btDiss.setOnClickListener {
            dismiss()
        }
        btSave.setOnClickListener {
            if (!RxPermissions.getInstance(c).isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                RxPermissions.getInstance(c).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe{
                            isOk->
                            if (isOk){
                                imgCheck.isDrawingCacheEnabled=true
                                val bitmap = Bitmap.createBitmap(imgCheck.drawingCache)
                                FileUtils.saveBitmap(bitmap,"datang${System.currentTimeMillis()}",c)
                                imgCheck.isDrawingCacheEnabled=false
                            }else{

                            }
                        }
            }else{
                imgCheck.isDrawingCacheEnabled=true
                val bitmap = Bitmap.createBitmap(imgCheck.drawingCache)
                FileUtils.saveBitmap(bitmap,"datang${System.currentTimeMillis()}",c)
                imgCheck.isDrawingCacheEnabled=false
            }
        }
    }
}